package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {
    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();

        List<Long> buyProductIds = createOrderContext.getBuyProductIds();

        if (StringUtils.isEmpty(buyProductIds)){
            //传统的方式
//            for (CartProductDto cartProductDto : dtoList) {
//                buyProductIds.add(cartProductDto.getProductId());
//            }
            //lambda的方式
            buyProductIds = dtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());
        }
        buyProductIds.sort(Long::compareTo);

        //查出库存 锁定库存
        List<Stock> stockList = stockMapper.findStocksForUpdate(buyProductIds);

        if (CollectionUtils.isEmpty(stockList)){
            throw new BizException("10000","库存未初始化");
        }
        if (stockList.size() != buyProductIds.size()){
            throw new BizException("10000","库存未初始化");
        }
        //扣减库存
        for (CartProductDto cartProductDto : dtoList) {
            @NotNull @Min(0) Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();
            //productNum不能超出我们限购的数量
            Integer restrictCount = stockMapper.selectStock(productId).getRestrictCount();
            if (productNum > restrictCount){
                throw new BizException("10000","超出限购数量");
            }

            //创建一个stock对象
            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);
            //将数据库中的lock_count和stock_count更新
            stockMapper.updateStock(stock);
        }
        return true;
    }
}